package com.jhws.sys.user.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jhws.business.feedback.bo.FeedbackConstant;
import com.jhws.business.local.service.LocalService;
import com.jhws.business.owner.bo.OwnerConstant;
import com.jhws.business.repair.bo.RepairConstant;
import com.jhws.business.repair.service.RepairService;
import com.jhws.business.feedback.service.FeedbackService;
import com.jhws.sys.user.bo.UserCommsBo;
import com.jhws.sys.user.service.UserCommsService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.sys.role.bo.TblRoleDimBo;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.bo.IndexMessage;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.util.security.CryptionData;
import com.jhws.util.GetId;
import com.jhws.common.base.bo.Global;
import com.jhws.sys.user.bo.TblUserDimForm;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.sys.role.service.ITblRoleDimService;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.commUtil;

/**
 * @author : Alex Tan
 * @Create : 2016-11-14 下午12:36:29
 * @Comment : Web用户管理模块控制器
 */
@Controller
@RequestMapping("/user")
public class UserCtrl {
    @Resource
    ITblCommDimService ITblCommDimService;

    @Resource
    ITblUserDimService IUserService;
    @Resource
    UserCommsService IUserCommsService;

    @Resource
    UserCommsService userCommsService;

    @Resource
    ITblRoleDimService ITblRoleDimService;

    @Resource
    ITblOwnerDimService IOwnerService;

    @Resource
    protected RedisTemplate stringTemplate;

    @Resource
    private FeedbackService feedbackService;

    @Resource
    private RepairService repairService;

    @Resource
    private LocalService localService;

    @RequestMapping("query.x")
    @ResponseBody
    public JsonRespData query(String logName,String commCode,String roleName)
            throws java.lang.Exception {
        return new JsonRespData("", 1, IUserService.findUserList(logName,commCode,roleName));

    }

    @RequestMapping("forSave.x")
    @RequiresRoles(value = {"admin", "secLevel"}, logical = Logical.OR)
    public String forSave(
            TblUserDimForm form, HttpServletRequest request) throws Exception {
        TblUserDimBo user = IUserService.currentUser();
        TblUserDimForm TblUserForm = (TblUserDimForm) form;
        boolean isNew = TblUserForm.getUserCode() == null
                || "".equals(TblUserForm.getUserCode());
        if (!isNew) {
            TblUserDimBo bo = IUserService.findTblUserDimById(
                    TblUserForm.getUserCode());
            request.setAttribute("defUser", bo);
        }
        String where = "";
        if (SecurityUtils.getSubject().hasRole(Global.ROLE_SEC_LEVEL_ADMIN))
            where = "where 1=1 and role_name = '" + Global.ROLE_PROPERTY_ADMIN + "'";

        List<TblRoleDimBo> list = ITblRoleDimService.findTblRoleDimByWhere(where);
        request.setAttribute("roleList", list);

        where = "where 1=1";
        if (SecurityUtils.getSubject().hasRole(Global.ROLE_SEC_LEVEL_ADMIN))
            where += " and comm_code in (" + commUtil.commCodesToSqlStr(user.getCommCode()) + ")";
        List<TblCommDimBo> commList = ITblCommDimService.findTblCommDimByWhere(where);
        request.setAttribute("commList", commList);

        return "/sys_mng/user/forSave";
    }

    @RequestMapping("save.x")
    @ResponseBody
    public JsonRespData save(TblUserDimForm TblUserForm) throws java.lang.Exception {
        TblUserDimBo bo = new TblUserDimBo();
        boolean isNew = TblUserForm.getUserCode() == null || "".equals(TblUserForm.getUserCode());

        TblUserDimBo user = IUserService.getLoginUserInfo(TblUserForm.getLogName());

        ModelAndView mv = new ModelAndView();
        String message;
        Map retMap = new HashMap<String, String>();
        if (isNew) {
            if (user != null) {
                message = "创建失败，用户名已存在！";
                return new JsonRespData("", -1, message);
            } else {
                BeanUtils.copyProperties(bo, TblUserForm);// 属性拷贝
                bo.setUserCode(GetId.randomID());

                if (StringUtils.isEmpty(TblUserForm.getLogPwd()))
                    bo.setLogPwd((new CryptionData()).EncryptionStringData("123456"));
                else if (null != TblUserForm.getLogPwd())
                    bo.setLogPwd((new CryptionData()).EncryptionStringData(TblUserForm.getLogPwd()));

                bo.setCreater(SecurityUtils.getSubject().getPrincipal().toString());
                TblRoleDimBo role = ITblRoleDimService.findTblRoleDimById(bo.getRoleCode());
                bo.setRoleName(role.getRoleName());
                if (StringUtils.isNotEmpty(TblUserForm.getCommCode())) {
                    UserCommsBo usercomm = new UserCommsBo();
                    usercomm.setUserName(bo.getLogName());
                    usercomm.setCommCode(TblUserForm.getCommCode());
                    usercomm.setRoleName((bo.getRoleName()));
                    IUserCommsService.save(usercomm);
                }
                IUserService.save(bo);
                message = "用户创建成功！";
                retMap.put("userCode", bo.getUserCode());
            }
        } else {
            user.setLogName(TblUserForm.getLogName());
            if (StringUtils.isNotEmpty(TblUserForm.getCommCode())) {
                IUserCommsService.removeByName(user.getLogName());
                UserCommsBo usercomm = new UserCommsBo();
                usercomm.setCommCode(TblUserForm.getCommCode());
                usercomm.setUserName(user.getLogName());
                usercomm.setRoleName(user.getRoleName());
                IUserCommsService.save(usercomm);
            }
            user.setRoleCode(TblUserForm.getRoleCode());
            user.setRoleName(TblUserForm.getRoleName());
            user.setCommCount(TblUserForm.getCommCount());
            IUserService.save(user);

            message = "修改用户信息成功！";
            retMap.put("userCode", user.getUserCode());
        }


        retMap.put("msg", message);

        return new JsonRespData("", 1, retMap);
    }

    @RequestMapping("remove.x")
    @ResponseBody
    public JsonRespData remove(String userCode) throws java.lang.Exception {

        TblUserDimBo user = IUserService.findTblUserDimById(userCode);
        IUserService.removeUserDim(userCode);
        IUserCommsService.removeByName(user.getLogName());
        return new JsonRespData("", 1, "");
    }

    @RequestMapping("view.x")
    @ResponseBody
    public JsonRespData view(String userCode) throws java.lang.Exception {

        TblUserDimBo user = IUserService.findTblUserDimById(userCode);

        List<Map> userCommsMap = IUserCommsService.findUserCommDetailsByName(user.getLogName());
        String logNameStr = "";

        for(int i=0;i<userCommsMap.size();i++){
            logNameStr += "【"+userCommsMap.get(i).get("commCode")+"】"+userCommsMap.get(i).get("commName")+"";
            if(i+1!=userCommsMap.size())
                logNameStr+=",";
        }

        user.setCommCode(logNameStr);
        return new JsonRespData("",1,user);
    }

    @RequestMapping("assignComm.x")
    @ResponseBody
    public JsonRespData assignComm(String userCode, String commCode, boolean isAdd) throws Exception {
        TblUserDimBo user = IUserService.findTblUserDimById(userCode);

		/* commCodes不为空表示点击了保存按钮 */
        if (StringUtils.isNotEmpty(commCode)) {
            if (isAdd) {
                String comms = "";
                /* 查找出分配的小区是否有被别的二级运营账号分配 */
                List<UserCommsBo> usercomms = userCommsService.findUserCommsByWhere(" where 1=1 and comm_code ='" + commCode + "' and user_name != '" + user.getLogName() + "'");
                if (usercomms != null && usercomms.size() > 0) {
                    for (UserCommsBo userCommsBo : usercomms) {
                        if (userCommsBo.getRoleName().equals(user.getRoleName()))
                            comms += "[" + userCommsBo.getCommCode() + ":" + userCommsBo.getUserName() + "],";
                    }
                }

                if (comms.length() > 0) {
                    return new JsonRespData("message", -1, "小区分配失败,以下小区已被分配<br>" + comms);
                }

                UserCommsBo bo = new UserCommsBo();
                bo.setCommCode(commCode);
                bo.setUserName(user.getLogName());
                bo.setRoleName(user.getRoleName());
                userCommsService.save(bo);
                return new JsonRespData("message", 1, "小区分配成功!");
            } else {
                userCommsService.removeByCommCode(user.getLogName(), commCode);
                return new JsonRespData("message", 1, "移除成功!");
            }
        }

        return new JsonRespData("message", -1, "小区不能为空!");
    }

    /**
     * 批量删除用户
     *
     * @return
     */
    @RequestMapping("removeBatchs.x")
    @ResponseBody
    public JsonRespData removeBatchs(@RequestBody TblUserDimBo[] users) throws Exception {
        for (TblUserDimBo user : users) {
            IUserService.removeUserDim(user.getUserCode());
            IUserCommsService.removeByName(user.getLogName());
        }
        return new JsonRespData("", 1, "");
    }

    @RequestMapping("updateMessageBox.x")
    @ResponseBody
    public JsonRespData updateMessageBox(HttpServletRequest request) throws Exception {
        /* 消息列表 */
        String where = "where 1=1 and apply_type = '" + OwnerConstant.OWNER_TYPE_APPLYING + "'";
        List<UserCommsBo> userCommsList = IUserCommsService.findUserCommsByName(IUserService.currentUser().getLogName());
        if (userCommsList != null && !userCommsList.isEmpty())
            where += " and commCode in (" + commUtil.userCommsToSqlStr(userCommsList) + ")";
        List<IndexMessage> retlist = new ArrayList<IndexMessage>();
        IndexMessage userInfoMsg;
        int count;
        TblUserDimBo user = IUserService.currentUser();
        if (com.jhws.util.StringUtils.isEmpty(user.getTelNum())) {
            userInfoMsg = new IndexMessage();
            if (request.getSession().getAttribute("userInfoLost") == null)
                userInfoMsg.setMsgType("userInfoMsg");
            userInfoMsg.setCount(1);
            userInfoMsg.setTitle("账号信息完善");
            userInfoMsg.setMessage("请完善管理员账号信息，以便找回密码");
            userInfoMsg.setUrl("/pages/sys_mng/user/forSaveUserInfo.html");
            retlist.add(userInfoMsg);
            request.getSession().setAttribute("userInfoLost", true);
        }

        count = feedbackService.findFeedbackCount("where state='" + FeedbackConstant.FEEDBACK_STATE_NOT_HANDLED + "'");
        if (count > 0 && SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
            userInfoMsg = new IndexMessage();
            userInfoMsg.setCount(count);
            userInfoMsg.setMsgType("feedbackInfoMsg");
            userInfoMsg.setTitle("用户反馈消息");
            userInfoMsg.setMessage("有" + count + "条用户反馈消息，请及时处理！");
            userInfoMsg.setUrl("/pages/business/feedback/query.html");
            retlist.add(userInfoMsg);
        }

        if (!SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)) {
            count = repairService.findRepairCount("where state='" + RepairConstant.REPAIR_STATE_UNTREATED + "' and comm_code in (" + IUserService.getUserCommsSqlStr(user) + ")");
            if (count > 0) {
                userInfoMsg = new IndexMessage();
                userInfoMsg.setCount(count);
                userInfoMsg.setMsgType("repairInfoMsg");
                userInfoMsg.setTitle("物业报修信息");
                userInfoMsg.setMessage("有" + count + "条物业报修消息，请及时处理！");
                userInfoMsg.setUrl("/pages/business/repair/query.html");
                retlist.add(userInfoMsg);
            }
        }

        return new JsonRespData("", 1, retlist);
    }

    @RequestMapping("getRolesAndPermissions.x")
    @ResponseBody
    public JsonRespData getRolesAndPermissions() {
        Map rolesAndPerms = new HashMap();
        TblUserDimBo user = IUserService.currentUser();
        TblRoleDimBo role = ITblRoleDimService.findTblRoleDimById(user.getRoleCode());

        rolesAndPerms.put("role", user.getRoleName() + "," + role.getRoleParents());
        List<String> perms = (List) SecurityUtils.getSubject().getSession().getAttribute("perms");
        if (perms != null) {
            /* 加入一些自定义平台权限给前端 */
            perms.addAll(IUserService.getPlatformPerms());
        }
        rolesAndPerms.put("perms", perms);
        rolesAndPerms.put("isLanMode", localService.isLanMode());
        return new JsonRespData("", 1, rolesAndPerms);
    }

    @RequestMapping("updateUserInfo.x")
    @ResponseBody
    public JsonRespData updateUserInfo(HttpServletRequest request, TblUserDimBo user) throws Exception {
        TblUserDimBo userInSession = IUserService.currentUser();
        TblUserDimBo userForMob = IUserService.getUserByName(user.getTelNum());
        if (userInSession.getUserCode().equals(user.getUserCode())) {
            if (userForMob != null && !userForMob.getUserCode().equals(userInSession.getUserCode()))
                return new JsonRespData("", -1, "该手机号已经被" + userForMob.getCommCode() + "小区的" + userForMob.getLogName() + "绑定!");
            userInSession.setTelNum(user.getTelNum());
            userInSession.setEmailAddress(user.getEmailAddress());
            userInSession.setUserName(user.getUserName());
            if (StringUtils.isNotEmpty(user.getLogPwd()))
                userInSession.setLogPwd((new CryptionData()).EncryptionStringData(user.getLogPwd()));
            IUserService.save(userInSession);
            request.getSession().setAttribute(TblUserDimBo.USER_INFO_REFERENCE, userInSession);
            return new JsonRespData("", 1, "");
        }

        return new JsonRespData("", -1, "没找到用户" + user.getLogName());
    }

    @RequestMapping("getCurrentUser.x")
    @ResponseBody
    public JsonRespData getCurrentUser() {
        TblUserDimBo user = IUserService.currentUser();
        if (user != null)
            return new JsonRespData("", 1, user);
        return new JsonRespData("", -1, "没获取到当前用户!");
    }

    @RequestMapping("getUserById.x")
    @ResponseBody
    public JsonRespData getUserById(String userCode) throws Exception {
        TblUserDimBo user = IUserService.findTblUserDimById(userCode);
        if (user != null) {
            /* 假如是物业账号,将小区编号顺带返回 */
            if (ITblRoleDimService.isRole(user.getRoleName(), Global.ROLE_PROPERTY_ADMIN)) {
                List<UserCommsBo> userCommsBoList = IUserCommsService.findUserCommsByName(user.getLogName());
                user.setCommCode(userCommsBoList.get(0).getCommCode());
            }
            return new JsonRespData("", 1, user);
        }
        return new JsonRespData("", -1, "没获取到用户!");
    }

    @RequestMapping("anon/getUserAuthInfo.x")
    @ResponseBody
    public JsonRespData getUserAuthInfo(String logName) throws Exception {
        TblUserDimBo user = IUserService.getUserByName(logName);
        if (user == null)
            return new JsonRespData("", -1, "此用户不存在");
        else {
            Map map = new HashMap<String, Object>();
            map.put("email", user.getEmailAddress());
            return new JsonRespData("", 1, map);
        }
    }

    /**
     * 前端获取某个用户的当前锁定状态
     *
     * @param userCode 用户的id
     * @return 返回locked表示当前用户被锁定, open表示正常
     */
    @RequestMapping("getUserState.x")
    @ResponseBody
    public JsonRespData getUserState(String userCode) {
        String ret;
        TblUserDimBo user = IUserService.findTblUserDimById(userCode);
        ValueOperations valueOperations = stringTemplate.opsForValue();
        String count = (String) valueOperations.get(Global.REDIS_LOGIN_LOCK_PREFIX + user.getLogName());
        if (count == null)
            count = "0";

        if (Integer.valueOf(count) == -1 || (Integer.valueOf(count) + 1) > Global.LOGIN_PASSWORD_FAIL_COUNT)
            ret = "locked";
        else
            ret = "open";

        return new JsonRespData("", 1, ret);
    }

    /**
     * 通过userCode获取当前用户管辖的所有小区列表
     *
     * @param userCode
     * @return
     */
    @RequestMapping("getUserComms.x")
    @ResponseBody
    public JsonRespData getUserComms(String userCode) {
        TblUserDimBo user = IUserService.findTblUserDimById(userCode);
        List<UserCommsBo> userCommsBoList = IUserCommsService.findUserCommsByName(user.getLogName());

        return new JsonRespData("", 1, userCommsBoList);
    }

    /**
     * 设置某个用户的锁定状态
     *
     * @param userCode 用户id
     * @param state    lock:永久锁定某个账号,unlock:解锁某个账号
     */
    @RequestMapping("setUserState.x")
    @ResponseBody
    public JsonRespData setUserState(String userCode, String state) {
        TblUserDimBo user = IUserService.findTblUserDimById(userCode);
        ValueOperations valueOperations = stringTemplate.opsForValue();
        if (state != null && state.equals("lock"))
            valueOperations.set(Global.REDIS_LOGIN_LOCK_PREFIX + user.getLogName(), "-1");
        else if (state != null && state.equals("unlock"))
            stringTemplate.delete(Global.REDIS_LOGIN_LOCK_PREFIX + user.getLogName());

        return new JsonRespData("", 1, "");
    }

    /**
     * 数据迁移的临时代码，部署后删除
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("debugUserDataMove.x")
    @ResponseBody
    public JsonRespData debugUserDataMove(String type) throws Exception {
        int count = 0;
        if ("setRole".equals(type)) {
            List<UserCommsBo> list = IUserCommsService.findUserCommsByWhere("");
            for (UserCommsBo userCommsBo : list) {
                TblUserDimBo user = IUserService.getUserByName(userCommsBo.getUserName());
                if (user != null) {
                    userCommsBo.setRoleName(user.getRoleName());
                    IUserCommsService.save(userCommsBo);
                    count++;
                }
            }
        } else {
            List<TblUserDimBo> userlist = IUserService.findTblUserDimByWhere("where 1=1");
            if (userlist != null && userlist.size() != 0) {
                for (TblUserDimBo user : userlist) {
                    if (StringUtils.isNotEmpty(user.getCommCode())) {
                        String[] comms = user.getCommCode().split(",");
                        UserCommsBo usercomm = new UserCommsBo();
                        usercomm.setCommCode(comms[0]);
                        usercomm.setUserName(user.getLogName());
                        usercomm.setRoleName(user.getRoleName());
                        user.setCommCode("");
                        IUserCommsService.save(usercomm);
                        IUserService.save(user);
                        count++;
                    }
                }
            }
        }
        return new JsonRespData("", 1, "移动了" + count + "个数据");
    }
}
